package com.chinaoly.sdk.image;

import android.annotation.SuppressLint;
import android.app.Application;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.support.annotation.DrawableRes;
import android.util.Log;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.GlideBuilder;
import com.bumptech.glide.RequestBuilder;
import com.bumptech.glide.RequestManager;
import com.bumptech.glide.load.MultiTransformation;
import com.bumptech.glide.load.Transformation;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.engine.bitmap_recycle.LruBitmapPool;
import com.bumptech.glide.load.engine.cache.LruResourceCache;
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions;
import com.bumptech.glide.request.RequestOptions;
import com.chinaoly.sdk.R;

import java.util.ArrayList;
import java.util.List;

import jp.wasabeef.glide.transformations.BlurTransformation;
import jp.wasabeef.glide.transformations.CropCircleTransformation;
import jp.wasabeef.glide.transformations.GrayscaleTransformation;
import jp.wasabeef.glide.transformations.RoundedCornersTransformation;

public class ImageManager {

    private Context mContext;

    @SuppressLint("VisibleForTests")
    public void init(Application application) {
        mContext = application;

        GlideBuilder builder = new GlideBuilder();

        // 设置缓存大小
        int memoryCacheSizeBytes = 1024 * 1024 * 20; // 20mb
        builder.setMemoryCache(new LruResourceCache(memoryCacheSizeBytes));

        // 设定 bitmap pool 大小
        int bitmapPoolSizeBytes = 1024 * 1024 * 30; // 30mb
        builder.setBitmapPool(new LruBitmapPool(bitmapPoolSizeBytes));

        builder.setLogLevel(getLogLevel());

        Glide.init(mContext, builder);
    }

    private static final ImageManager ourInstance = new ImageManager();

    public static ImageManager getInstance() {
        return ourInstance;
    }

    private ImageManager() {

    }

    public void perload() {
    }

    /**
     * 清空内存缓存。建议在BaseActivity的onLowMemory方法里调用
     */
    public void clearMemory() {
        Glide.get(mContext).clearMemory();
    }

    /**
     * 清空磁盘缓存（不建议使用）
     */
    public void clearDiskCache() {
        Glide.get(mContext).clearDiskCache();
    }

    /**
     * 根据不同的内存状态，来响应不同的内存释放策略。建议在BaseActivity的onTrimMemory方法里调用
     *
     * @param level
     */
    public void trimMemory(int level) {
        Glide.get(mContext).trimMemory(level);
    }

    public void log() {

    }

    @SuppressLint("CheckResult")
    public void loadImage(ImageView view, String url, int radius, boolean isRound, boolean isDecolor, int blurRadius, int blurSampling,
                          int left_top_radiu, int right_top_radiu, int left_bottom_radiu, int right_bottom_radiu,
                          int placeHolder, int fallback, int error,
                          boolean asBitmap, boolean asGif, int crossFade,
                          boolean centerCrop, boolean centerInside, boolean fitCenter,
                          Transformation finalTransformation) {
        RequestManager manager = Glide.with(mContext);
        RequestBuilder<Drawable> request = manager.load(url);
        RequestOptions requestOptions = new RequestOptions();

        // Transformation
        List<Transformation> transformationList = new ArrayList<>();

        // 圆形和圆角矩形
        if (isRound) {
            transformationList.add(new CropCircleTransformation());
        } else if (left_top_radiu != 0
                || right_top_radiu != 0
                || left_bottom_radiu != 0
                || right_bottom_radiu != 0) {
            // TODO: 2018/7/9 每个圆角半径都不一样的圆角矩形
        } else if (radius != 0) {
            transformationList.add(new RoundedCornersTransformation(radius, 0));
        }

        // 高斯模糊
        if (blurRadius != 0 || blurSampling != 0) {
            transformationList.add(new BlurTransformation(blurRadius == 0 ? 10 : blurRadius, blurSampling == 0 ? 1 : blurSampling));
        }

        // 去色
        if (isDecolor) {
            transformationList.add(new GrayscaleTransformation());
        }

        // 其他
        if (finalTransformation != null) {
            transformationList.add(finalTransformation);
        }

        if (transformationList.size() > 0) {
            Transformation[] transformations = transformationList.toArray(new Transformation[transformationList.size()]);
            MultiTransformation multiTransformation = new MultiTransformation(transformations);
            request = request.apply(RequestOptions.bitmapTransform(multiTransformation));
        }

        // 占位图
        if (placeHolder == 0) {
            placeHolder = getDefaultPlaceHolder();
        }
        requestOptions = requestOptions.placeholder(placeHolder);
        if (fallback == 0) {
            fallback = getDefaultFallback();
        }
        requestOptions = requestOptions.fallback(fallback);
        if (error == 0) {
            error = getDefaultError();
        }
        requestOptions = requestOptions.error(error);

        // 缩放方式
        if (centerCrop) {
            requestOptions = requestOptions.centerCrop();
        } else if (centerInside) {
            requestOptions = requestOptions.centerInside();
        } else if (fitCenter) {
            requestOptions = requestOptions.fitCenter();
        }

        // 磁盘缓存
        requestOptions = requestOptions.diskCacheStrategy(DiskCacheStrategy.ALL);

        request = request.apply(requestOptions);
        // 图片渐显时间
        if (crossFade != 0) {
            request.transition(new DrawableTransitionOptions().crossFade(crossFade));
        }

        request.into(view);
    }

    private int getDefaultPlaceHolder() {
        return defaultPlaceHolder == 0 ? R.drawable.ic_default : defaultPlaceHolder;
    }

    /**
     * 设置默认的资源加载过程中的图。建议在初始化时调用
     *
     * @param defaultPlaceHolder
     */
    public void setDefaultPlaceHolder(int defaultPlaceHolder) {
        this.defaultPlaceHolder = defaultPlaceHolder;
    }

    private int getDefaultFallback() {
        return defaultFallback == 0 ? R.drawable.ic_default : defaultFallback;
    }

    /**
     * 设置默认的空图。建议在初始化时调用
     *
     * @param defaultFallback
     */
    public void setDefaultFallback(int defaultFallback) {
        this.defaultFallback = defaultFallback;
    }

    private int getDefaultError() {
        return defaultError == 0 ? R.drawable.ic_default : defaultError;
    }

    /**
     * 设置默认的加载失败图。建议在初始化时调用
     *
     * @param defaultError
     */
    public void setDefaultError(int defaultError) {
        this.defaultError = defaultError;
    }

    public int getLogLevel() {
        return (logLevel < 2 || logLevel > 7) ? Log.DEBUG : logLevel;
    }

    public void setLogLevel(int logLevel) {
        this.logLevel = logLevel;
    }

    @DrawableRes
    private int defaultPlaceHolder;
    @DrawableRes
    private int defaultFallback;
    @DrawableRes
    private int defaultError;

    private int logLevel;

}